package com.bulletelc.apollopre.framework;

import android.support.annotation.UiThread;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

/**
 * author: lhl
 * date  : 2017/10/30
 * desc  : 通过弱引用和Activity以及Fragment的生命周期预防内存泄露的问题
 */

public abstract class BasePresenter<V extends IView> implements IPresenter<V>{

    /**
     * View 接口类型的弱引用
     */
    protected Reference<V> viewRef;

    @UiThread
    @Override
    public void attachView(V view) {
        viewRef = new WeakReference<V>(view);
    }

    protected V getView() {
        return viewRef == null ? null : viewRef.get();
    }

    public boolean isViewAttached() {
        return viewRef != null && viewRef.get() != null;
    }

    @UiThread
    @Override
    public void detachView(boolean retainInstance) {
        if (viewRef != null) {
            viewRef.clear();
            viewRef = null;
        }
    }
}
